package demo1;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private Integer serverPort;
    private String serverIp;
    DatagramSocket datagramSocket;

    public UdpEchoClient(String serverIp, Integer serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        //构造网卡
        datagramSocket = new DatagramSocket();
    }

    public void start() throws Exception {
        System.out.println("客户端启动");
        System.out.println("输入你要发送的请求");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), 0, request.getBytes().length, InetAddress.getByName(serverIp), serverPort);
            System.out.println("发送的请求" + request);
            datagramSocket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            datagramSocket.receive(responsePacket);
            String reponse = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println("服务器响应:" + reponse);
        }
    }

    static void main() throws Exception {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }

}
